package com.shadow.cloud.security.controller;

import com.shadow.cloud.common.bo.R;
import com.shadow.cloud.security.dto.OrgDTO;
import com.shadow.cloud.security.entity.OrgEntity;
import com.shadow.cloud.security.service.OrgService;
import com.shadow.cloud.security.utils.ant.AntTreeNode;
import com.shadow.cloud.security.utils.ant.AntUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("org")
public class OrgController {

    private final OrgService orgService;

    @GetMapping("getOrgTree")
    public R getOrgTree() {
        List<OrgEntity> list = orgService.list();
        List<AntTreeNode> orgDTOList = AntUtils.convertToTree(list);
        return R.success(R.SUCCESS_MSG, orgDTOList);
    }




    public static List<OrgDTO> convertToTree(List<OrgEntity> list) {
        // 1. 转换 A -> ADTO
        List<OrgDTO> dtoList = list.stream()
                .map(a -> {
                    OrgDTO dto = new OrgDTO();
                    dto.setId(a.getId());
                    dto.setParentId(a.getParentId());
                    dto.setName(a.getName());
                    return dto;
                }).collect(Collectors.toList());
        // 2. 构建树形结构
        Map<String, OrgDTO> dtoMap = dtoList.stream()
                .collect(Collectors.toMap(OrgDTO::getId, dto -> dto));

        List<OrgDTO> rootList = new ArrayList<>();
        for (OrgDTO dto : dtoList) {
            if (StringUtils.equals(dto.getParentId(), "1")) {
                // 如果没有父级，则为根节点
                rootList.add(dto);
            } else {
                // 找到父级节点，将当前节点添加到父级的 children 中
                OrgDTO parent = dtoMap.get(dto.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(dto);
                }
            }
        }
        return rootList;
    }
}
